#!/bin/sh
# function_library: logging functions and release number conversion (ex: 4.9.0 -> 40900)

echo_binary=$(which echo)

if [ "$echo_binary" = "" ]
then
  echo_binary="echo"
fi
if [ "$($echo_binary -e test)" = "-e test" ]
then
  enable_colors="false"
else
  enable_colors="true"
fi

COLOR_NC='\e[0m' # No Color
COLOR_BLACK='\e[0;30m'
COLOR_BLUE='\e[0;34m'
COLOR_BROWN='\e[0;33m'
COLOR_GRAY='\e[0;30m'
COLOR_GREEN='\e[0;32m'
COLOR_CYAN='\e[0;36m'
COLOR_RED='\e[0;31m'
COLOR_PURPLE='\e[0;35m'
COLOR_WHITE='\e[1;37m'
COLOR_YELLOW='\e[1;33m'
COLOR_LIGHT_BLUE='\e[1;34m'
COLOR_LIGHT_CYAN='\e[1;36m'
COLOR_LIGHT_GRAY='\e[0;37m'
COLOR_LIGHT_GREEN='\e[1;32m'
COLOR_LIGHT_PURPLE='\e[1;35m'
COLOR_LIGHT_RED='\e[1;31m'

# for((i=0; i<256; i++)); do printf "\e[48;5;${i}m%03d" $i; printf '\e[0m'; [ ! $((($i - 15) % 6)) -eq 0 ] && printf ' ' || printf '\n'; done

### Function declarations

# Enable standard echo behaviour everywhere
echo()
{
  $echo_binary "$@"
}
log_debug()
{
  if [ -t 1 -a "$enable_colors" = "true" ] # If file descriptor fd is open and refers to a terminal.
  then
    # echo every parameters to stdout
    echo -e "$@"
  else # else, remove output colorisation with sed (usefull for pipe or file redirection)
    echo "$@" | sed -e 's/\\e\[[[:digit:]]\{1,3\}\(;[[:digit:]]\{1,3\}\)*m//g' 
  fi
}
log_debug_info()
{
  if [ "$show_debug_info" = "true" ]
  then
    log_debug "${COLOR_GREEN}$SCRIPT_NAME INFO:${COLOR_NC}" "$@"
  fi
}
log_debug_warning()
{
  if [ "$show_debug_warning" = "true" ]
  then
    log_debug "${COLOR_BROWN}$SCRIPT_NAME WARNING:${COLOR_NC}" "$@"
  fi
}
log_debug_error()
{
  if [ "$show_debug_error" = "true" ]
  then
    log_debug "${COLOR_RED}$SCRIPT_NAME ERROR:${COLOR_NC}" "$@"
  fi
}
convert_version_to_number()
{
  if [ -z "$1" ]
  then
    log_debug_error "Function 'convert_version_to_number' called with empty parameter"
    return 1
  fi
  echo "$1" | sed -e 's/\.\([0-9][0-9]\)/\1/g' -e 's/\.\([0-9]\)/0\1/g' -e 's/^[0-9]\{3,4\}$/&00/' -e 's/^[0-9]\{1,2\}$/&0000/'
  return 0
}
